const Excel = require('exceljs');
const fs = require('fs');
const path = require('path');
const resolvePath = filePath => path.resolve(__dirname, filePath);

if (!fs.existsSync(resolvePath('./export'))) {
    fs.mkdirSync(resolvePath('./export'));
}


async function exportExcel(data) {
    if (!Array.isArray(data)) {
        data = [];
    }
    let workbook = new Excel.Workbook();
    let templatePath = path.resolve(__dirname, './exportTemplate.xlsx');
    await workbook.xlsx.readFile(templatePath);
    let sheet = workbook.getWorksheet(1);
    for (const item of data) {
        let rowValues = [
            '',
            item.siteName,
            item.date,
            item.keywords
        ];
        sheet.addRow(rowValues);
        let row = sheet.getRow(sheet.rowCount);
        row.getCell(1).value = { text: item.title, hyperlink: item.link };
        row.height = Math.ceil(item.title.length / 30) * 15;
    }
    let fileName = getExportExcelName();
    let filePath = resolvePath(`./export/${fileName}`);
    await workbook.xlsx.writeFile(filePath);
    return `excel/export/${fileName}`;
}

function getExportExcelName() {
    let now = new Date();
    return `爬取结果导出-${now.getFullYear()}${now.getMonth() + 1}${now.getDate()}${now.getHours()}${now.getMinutes()}${now.getSeconds()}${now.getMilliseconds()}.xlsx`;
}


module.exports = {
    exportExcel
}